package com.zhiyun.hxzy.controller.user;

import com.zhiyun.hxzy.domain.Collection;
import com.zhiyun.hxzy.domain.Student;
import com.zhiyun.hxzy.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user/collection")
public class CollectionController {
    @Autowired
    private CollectionService collectionService;

    //收藏或取消收藏
    @RequestMapping("/addOrCancel")
    public @ResponseBody
    void addOrCancel1(Long homeworkId, HttpSession session, int num) {
        Student student = (Student) session.getAttribute("student");
        collectionService.findByStudentIdAndHomeworkId(student.getId(), homeworkId);
    }

    //收藏后返回该作业被收藏的总数
    @RequestMapping("/findCollection")
    public @ResponseBody
    int findCollection(Long homeworkId) {
        return collectionService.findCollectionsByHomeworkId(homeworkId);
    }

    //查询该用户是否收藏该作业
    @RequestMapping("/findCollectionByHomeworkIdAndstudentId")
    public @ResponseBody
    boolean findCollectionByHomeworkIdAndstudentId(Long homeworkId, HttpSession session) {
        Student student = (Student) session.getAttribute("student");
        if (student == null){
            return false;
        }
        return collectionService.findByStudentIdAndHomeworkId2(homeworkId, student.getId());
    }

    //异步返回至我的收藏
    @RequestMapping("/findCollectionByStudentId")
    public @ResponseBody
    Page<Collection> findCollectionByStudentId(HttpSession session, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "9") int pageSize) {
        Student student = (Student) session.getAttribute("student");
        Page<Collection> byStudentId = collectionService.findByStudentId(student.getId(), pageNum, pageSize);
        return byStudentId;
    }
    //异步取消收藏
    @RequestMapping("/cancelCollection")
    public @ResponseBody Page<Collection> cancelCollection(@RequestParam(defaultValue = "1")int pageNum,@RequestParam(defaultValue = "9")int pageSize, Long homeworkId,HttpSession session){
        Student student = (Student) session.getAttribute("student");
        collectionService.findByStudentIdAndHomeworkId(student.getId(),homeworkId);
        return collectionService.findByStudentId(student.getId(),pageNum,pageSize);
    }

}
